#include <WinSock2.h>
#include "Server.h"

//
#include <iostream>
using namespace std;

#include "Game.h"

int Server::run()
{
	// 2rd processor
	HANDLE threadId = GetCurrentThread();
	DWORD_PTR processAffinityMask = 2;
	SetThreadAffinityMask(threadId, processAffinityMask);

	int nextAvailablePort = 9173;

	char buffer;
	sockaddr_in clientAddr;
	int addrSize = sizeof(clientAddr);
	
	unsigned int connectionID = 0;

	std::cout << "Listening for UDP messages from clients" << std::endl;

	while (!m_bTerminate)
	{

		std::cout << "-------------------------------------------------------------" << std::endl;

		// receive
		if (recvfrom(m_listeningSocket, &buffer, 1, 0, (sockaddr*)&clientAddr, &addrSize) == SOCKET_ERROR)
		{
			cerr << "receive failed with " << WSAGetLastError() << endl;
		}

		std::cout << "Received new UDP message" << std::endl;
		
		if (buffer != '$') 
			continue;
		

		std::cout << "UDP message valid" << std::endl;


		if (sendto(m_listeningSocket, (char*)&nextAvailablePort, 4, 0, (sockaddr*)&clientAddr, addrSize) == SOCKET_ERROR) {
			cerr << "send failed with " << WSAGetLastError() << endl;
		}

		Connection conn(this);
		connections.push_back(conn);
		connections[connections.size()-1].start(connectionID, nextAvailablePort);
		connectionID++;
		nextAvailablePort++;
	}
	return 0;
}



int Server::init()
{
	// Create version identifier
	WORD wVersionRequested = MAKEWORD( 2, 0 );

	// Startup windows sockets
	WSADATA wsaData;
	if ( WSAStartup( wVersionRequested, &wsaData )) {
		cerr << "Socket initialisation failed" << endl;
		return -1;
	}

	sockaddr_in peer;
	peer.sin_family = AF_INET;
	peer.sin_port = htons(9171);	// port 9171
	peer.sin_addr.S_un.S_addr = htonl( INADDR_ANY );

	// Create listening socket - UDP
	m_listeningSocket = socket(AF_INET, SOCK_DGRAM, 0);

	if (m_listeningSocket==INVALID_SOCKET) {
		cerr << "Create socket failed" << endl;
	} else if (bind(m_listeningSocket, (sockaddr *)&peer, sizeof(peer))==SOCKET_ERROR) {
		cerr << "Bind failed with " << WSAGetLastError()  << endl;
	} 

	m_bufferSize = 0;

	return 0;
}


void Server::connectionError(int id)
{
	
}